﻿using AutoMapper;
using QYmall.Core.API.Filters;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace QYmall.Core.API.Controllers
{
    /// <summary>
    /// 订单统计报表
    /// </summary>
    [Route("admin/report/order")]
    [ApiController]
    public class ReportOrderController : ControllerBase
    {
        private readonly IReportOrderService _reportOrderService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public ReportOrderController(IReportOrderService reportOrderService, IUserService userService, IMapper mapper)
        {
            _reportOrderService = reportOrderService;
            _userService = userService;
            _mapper = mapper;
        }

        #region 管理员调用接口==========================
        /// <summary>
        /// 获取商户销售统计
        /// 示例：/admin/report/order/merchant/count
        /// </summary>
        [HttpGet("merchant/count")]
        [Authorize]
        public async Task<IActionResult> GetMerchantCount([FromQuery] ReportParameter searchParam)
        {
            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            }
            if (searchParam.EndTime == null)
            {
                searchParam.EndTime = DateTime.Now;
            }
            if (searchParam.Top <= 0 || searchParam.Top > 10)
            {
                searchParam.Top = 10;
            }
            var result = await _reportOrderService.GetMerchantSaleCountAsync(searchParam.Top.GetValueOrDefault(),
                x => (searchParam.Status == -1 || searchParam.Status == x.Status)
                && (DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
            );
            return Ok(result);
        }

        /// <summary>
        /// 获取商品销售统计
        /// 示例：/admin/report/order/goods/count
        /// </summary>
        [HttpGet("goods/count")]
        [Authorize]
        public async Task<IActionResult> GetGoodsCount([FromQuery] ReportParameter searchParam)
        {
            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            }
            if (searchParam.EndTime == null)
            {
                searchParam.EndTime = DateTime.Now;
            }
            var result = await _reportOrderService.GetGoodsSaleCountAsync(searchParam.Top.GetValueOrDefault(),
                x => (DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
            );
            return Ok(result);
        }

        /// <summary>
        /// 获取商品销售分页
        /// 示例：/admin/report/order/goods/list
        /// </summary>
        [HttpGet("goods/list")]
        [Authorize]
        [AuthorizeFilter("ReportOrder", ActionType.View, "Goods")]
        public async Task<IActionResult> GetGoodsList([FromQuery] ReportParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            }
            if (searchParam.EndTime == null)
            {
                searchParam.EndTime = DateTime.Now;
            }

            //获取数据列表
            var list = await _reportOrderService.GetGoodsSalePageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.Order != null
                && (DateTime.Compare(x.Order.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (DateTime.Compare(x.Order.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0),
                searchParam.OrderBy ?? "Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO
            var resultDto = _mapper.Map<IEnumerable<OrderGoodsDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取订单金额统计
        /// 示例：/admin/report/order/amount/count
        /// </summary>
        [HttpGet("amount/count")]
        [Authorize]
        public async Task<IActionResult> GetAmountCount([FromQuery] ReportParameter searchParam)
        {
            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            }
            if (searchParam.EndTime == null)
            {
                searchParam.EndTime = DateTime.Now;
            }
            var result = await _reportOrderService.GetOrderAmountCountAsync(searchParam.Top.GetValueOrDefault(),
                x => (DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
            );
            return Ok(result);
        }

        /// <summary>
        /// 获取订单金额分页
        /// 示例：/admin/report/order/amount/list
        /// </summary>
        [HttpGet("amount/list")]
        [Authorize]
        [AuthorizeFilter("ReportOrder", ActionType.View, "Amount")]
        public async Task<IActionResult> GetAmountList([FromQuery] ReportParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            }
            if (searchParam.EndTime == null)
            {
                searchParam.EndTime = DateTime.Now;
            }

            //获取数据列表
            var list = await _reportOrderService.GetOrderAmountPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => (DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0),
                searchParam.OrderBy ?? "AddTime,Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO
            var resultDto = _mapper.Map<IEnumerable<OrdersDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }
        #endregion

        #region 商家调用接口============================
        /// <summary>
        /// 获取订单金额统计
        /// 示例：/merchant/report/order/amount/count
        /// </summary>
        [HttpGet("/merchant/report/order/amount/count")]
        [Authorize]
        public async Task<IActionResult> MerchantAmountCount([FromQuery] ReportParameter searchParam)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _reportOrderService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddDays(-DateTime.Now.Day + 1);
            }
            if (searchParam.EndTime == null)
            {
                searchParam.EndTime = DateTime.Now;
            }
            var result = await _reportOrderService.GetOrderAmountCountAsync(searchParam.Top.GetValueOrDefault(),
                x => x.MerchantId == merchantModel.Id
                && (DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
            );
            return Ok(result);
        }
        #endregion
    }
}
